/***************************************************************************
 *   Copyright (C) 2007 by Luca Bellonda                                   *
 *   lbell @ tsc4.com                                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

package lb.prove;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Message;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Process;
import android.util.Log;

public class ReadRSSService extends Service implements Runnable {
	
	public static final String URL_DEFAULT = "http://planetkde.org/rss20.xml";
	static final int DAYS_AUTO_DELETE = 30;
	//public static final String URL_DEFAULT = "http://planet.gnome.org/rss20.xml";		
    private NotificationManager		mNotificationManager;
    private Intent					mInvokeIntent;
    private volatile Looper			mServiceLooper;
    private volatile ServiceHandler	mServiceHandler;
	String sourceUrl = URL_DEFAULT;
    
    @Override
    protected void onCreate()
    {
    	Log.i("ReadRSSService", "created" );
    	mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        Intent intent = new Intent();
        intent.setClass(this, PlanetFeedsRead.class);

        Thread serviceThread = new Thread(null, this, "ReadRSSService");
        serviceThread.start();
    }
    @Override
    protected void onStart(int startId, Bundle arguments)
    {
    	Log.i("ReadRSSService", "Starting #" + startId + ": " + arguments);
        while (mServiceHandler == null)
        {
            synchronized (this) {
                try {
                    wait(100);
                } catch (InterruptedException e)
                {
                }
            }
        }
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1	= startId;
        msg.obj		= arguments;
        mServiceHandler.sendMessage(msg);
        Log.i("ReadRSSService", "Sending: " + msg);
    }
    
    @Override
    protected void onDestroy()
    {
        while (mServiceLooper == null) {
            synchronized (this) {
                try {
                    wait(100);
                } catch (InterruptedException e) {
                }
            }
        }
        mServiceLooper.quit();
        mNotificationManager.cancel(R.string.srv_started);
        mNotificationManager.notifyWithText(R.string.srv_stopped,
                   getText(R.string.srv_stopped),
                   NotificationManager.LENGTH_SHORT,
                   null);
    }
    
    public void run()
    {
        Looper.prepare();

        mServiceLooper = Looper.myLooper();
        mServiceHandler = new ServiceHandler();

        Looper.loop();
    }
    final long NORMALTIMEOUT = 15*60*1000;
    //final long NORMALTIMEOUT = 4*1000;
    long intervalBetweenReadMS = NORMALTIMEOUT;
    boolean shouldStop = false;
    private long clipTimeoutRead(final long timeout)
    {
    	if(timeout<0)
    		return NORMALTIMEOUT;
    	if( timeout>(10*NORMALTIMEOUT) )
    		return 10*NORMALTIMEOUT;
    	return timeout;
    }
    private final class ServiceHandler extends Handler
    {
	    @Override
	    public void handleMessage(Message msg)
	    {
	        Bundle arguments = (Bundle)msg.obj;
	        String txt = getResources().getString(R.string.srv_started);
	        intervalBetweenReadMS = arguments.getLong("readTimeout");
	        intervalBetweenReadMS = clipTimeoutRead(intervalBetweenReadMS);
	
	        Log.i("ServiceStartArguments", "Message: " + msg + ", " + txt);
	
	        mNotificationManager.notifyWithText(R.string.srv_started,
	                   txt,
	                   NotificationManager.LENGTH_SHORT,
	                   new Notification(
	                       R.drawable.srvstrt,
	                       getText(R.string.srv_label),
	                       mInvokeIntent,
	                       null,
	                       null));
	        long endTime ;
	        while( !shouldStop )
	        {
	            endTime = System.currentTimeMillis() + intervalBetweenReadMS ;
	            synchronized (this) {
	                try {
	                	if( readFeeds() )
	                	{
	            	        mNotificationManager.notify(R.string.srv_new_feeds,
	         	                   new Notification(
	         	                       R.drawable.srv,
	         	                       getText(R.string.srv_new_feeds),
	         	                       mInvokeIntent,
	         	                       null,
	         	                       null));
	                	}
	                    wait(endTime - System.currentTimeMillis());
	                } catch (Exception e)
	                {
	                }
	            }
	        }
	        Log.i("ReadRSSService", "Done" );
	        stopSelf(msg.arg1);
	    }
	    private boolean readFeeds()
	    {
	    	DBHelper dbHelper = new DBHelper(getApplication());
	    	RssRead rss = new RssRead();
	    	dbHelper.eraseOldRows(DAYS_AUTO_DELETE);
	    	boolean newEntries = rss.getRSSEntries(sourceUrl,getApplication(),dbHelper);
	    	dbHelper.close();
	    	dbHelper = null;
	    	return newEntries ;
	    }
    };
    @Override
    public IBinder getBinder()
    {
        return mBinder;
    }

    private final IReadService.Stub mBinder = new IReadService.Stub() {
        public int getPid() {
            return Process.myPid();
        }
        public void setReadTimeout(long minutes){
            synchronized (this) {
                try {
                	intervalBetweenReadMS = clipTimeoutRead(minutes*60*1000);
                } catch (Exception e)
                {
                }
            }
        }
        public void setDeleteTimeout(long days){}
        public void setUrl(String newUrl) {
	        synchronized (this) {
	            try {
	            	sourceUrl = newUrl;
	            	if((null==sourceUrl)||(0==sourceUrl.length()))
	            		sourceUrl = URL_DEFAULT;
	            } catch (Exception e)
	            {
	            	sourceUrl = URL_DEFAULT;
	            }
	        }
        }
    };
}
